package com.lagou.edu.utils;

import com.alibaba.druid.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class FileScanUtils {
    private static final String encodeSeparator = "%5c";
    private static final String clazzSuffix = ".class";

    public static List<String> scanAllClassFiles(String basePackage) {
        if (StringUtils.isEmpty(basePackage)) {
            return new ArrayList<>();
        }

        final List<String> result = new ArrayList<>();

        String basePackagePath = basePackage.replace(".", File.separator);

        ClassLoader classLoader = FileScanUtils.class.getClassLoader();
        Stream<URL> resources = classLoader.resources(basePackagePath);
        resources.forEach(t -> {
            List<String> AllClassFileName = new ArrayList<>();
            String path = t.getPath();
            path = path.replace(encodeSeparator, File.separator);
            File file = new File(path);
            getAllClassFileName(file, AllClassFileName);
            // 处理className的问题
            List<String> collect = AllClassFileName.stream().map(classFileName -> {
                int start = classFileName.indexOf(basePackagePath);
                // 保留相对路径
                String substring = classFileName.substring(start);
                // 去掉末尾的.class
                String classNameContainsSuffix = substring.substring(0, substring.indexOf(clazzSuffix));
                // 得到类文件名称
                String className = classNameContainsSuffix.replace(File.separator, ".");
                return className;
            }).collect(Collectors.toList());

            result.addAll(collect);
        });
        return result;
    }

    private static void getAllClassFileName(File file, List<String> allClassName) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File childFile : files) {
                getAllClassFileName(childFile, allClassName);
            }
        } else {
            allClassName.add(file.getPath());
        }
    }
}
